<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta
            name="viewport"
            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
    >
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>滚动到列表底部自动加载新数据</title>
    <style>
        .list {
            overflow: auto;
            height: 200px;
            border: 1px solid #CCCCCC;
        }
        .list-item {
            margin-top: 10px;
        }
    </style>
</head>
<body>
<ul class="list"></ul>
<script>
    let counts = 0;
    const list = document.querySelector(".list");
    function renderListItem(text, id) {
        const li = document.createElement("li");
        li.textContent = text;
        li.id = id;
        li.classList.add("list-item");
        return li;
    }
    function renderList(count) {
        const frag = document.createDocumentFragment();
        for (let i = 0; i < count; i++) {
            frag.appendChild(renderListItem(`${counts + i + 1}-item`, `item-${Date.now()}-${i}`));
        }
        list.appendChild(frag);
        counts+=count;
    }
    function loadData() {
        renderList(10);
    }
    loadData();
    
    function implWithIntersection() {
        function observeLastChild() {
            observe.disconnect();
            observe.observe(list.lastChild);
        }
        const observe = new IntersectionObserver((entries) => {
            if (entries[0].isIntersecting) {
                loadData();
                observeLastChild();
            }
        });
        observeLastChild();
    }
    function implWithScroll() {
        list.addEventListener("scroll", function(ev) {
            if ((ev.target.clientHeight + ev.target.scrollTop) >= (ev.target.scrollHeight - 50)) {
                loadData();
            }
        })
    }
    implWithScroll();
</script>
</body>
</html>